from fastapi import Request,Response
from starlette.middleware.base import BaseHTTPMiddleware
import time


# 定义请求拦截器
class RequestInterceptor(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        print(f"Request from {request.client.host}")
        start_time = time.perf_counter()

        # if request.method == "OPTIONS":
        #     return Response(status_code=403, headers={
        #         "Access-Control-Allow-Origin": "*",
        #         "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",
        #         "Access-Control-Allow-Headers": "*",
        #         "X-Lin-Web": "StarBucket",
        #         "X-Confine-Method": "OPTIONS",
        #     })

        response: Response = await call_next(request)
        process_time = time.perf_counter() - start_time
        response.headers["X-Lin-Web"] = "StarBucket"
        response.headers["X-Process-Time"] = str(process_time)

        return response
